/* GSManufactureWriteAction.java
 *
 * Project/Product: APEP-JZCG
 *
 * Modify Information:
 * =============================================================================
 *   Author	Date       Description
 *   ----------	---------- ---------------------------------------------------
 *   peng.ning	2008-10-28	First release
 *
 * Licensed Materials - Property of APEP
 * =============================================================================
 *    (C) COPYRIGHT Shanghai Auto Mart E-Procurement Co., Ltd. 2007 - 2008
 *    All Rights Reserved.
 *
 *    This software is the confidential and proprietary information of
 *    Shanghai Auto Mart E-Procurement Co., Ltd. ("Confidential Information").
 *    You shall not disclose such Confidential Information and shall use it only
 *    in accordance with the terms of the license agreement you entered into 
 *    with Shanghai Auto Mart E-Procurement Co., Ltd.
 *
 * Noties:
 * =============================================================================
 * 
 */

package com.hitrust.gs.action;

import java.util.ArrayList;

import system.LoginContext;
import system.base.Warehouse;

import com.hitrust.gs.bean.GSManufactureBean;
import com.hitrust.gs.bean.GSTemporaryProductBean;
import com.hitrust.gs.bean.GSWareHouseBean;
import com.hitrust.gs.business.GSManufactureProcessor;
import com.hitrust.gs.dao.GSManufactureDAO;
import com.hitrust.gs.dao.GSTemporaryProductDao;
import com.hitrust.gs.form.GSManufactureAddForm4;
import com.hitrust.gs.lib.GSBaseConstants;
import com.hitrust.gs.lib.GSLogWriter;
import com.hitrust.gs.lib.GSSystemConfigurator;
import com.hitrust.gs.lib.db.GSBaseDAO;
import com.hitrust.gs.service.GSBaseAction;
import com.hitrust.gs.service.GSBaseForm;
import com.hitrust.gs.service.GSBaseManager;
import com.hitrust.gs.util.exception.GSException;
import com.hitrust.gs.util.page.ResultProcess;
import com.hitrust.gs.vo.GSManufactureVO;
import com.hitrust.gs.vo.GSTemporaryManufactureView;

import framework.core.DBConnection;
import framework.core.DateUtil;
import framework.core.ObjectList;

public class GSTemporaryManufactureInSteadWriteAction extends GSBaseAction {

    /*
     * (non-Javadoc)
     * 
     * @see com.apep.jzcg.service.GSBaseAction#execute(com.apep.jzcg.service.GSBaseForm)
     */
    public String execute(GSBaseForm aForm) throws Exception {
        // TODO Auto-generated method stub
        GSManufactureProcessor processor = new GSManufactureProcessor();
        GSManufactureDAO dao = new GSManufactureDAO();
        GSManufactureAddForm4 form = (GSManufactureAddForm4) aForm;
        LoginContext context = (LoginContext) form.getSession().getAttribute(GSBaseConstants.LOGIN);
        String[] index = form.getSel_manufacture();
        String[] rid = form.getGs_recorder_id();
        ResultProcess rst = (ResultProcess) aForm.getSession().getAttribute("manufactureExcel");
        ArrayList array = rst.getAllRecoreds();
        boolean flag = false;
        Object modify = aForm.getSession().getAttribute("modify");
        if(modify!=null&&modify.toString().equals("true")){
           // flag = true;
        }
        GSTemporaryProductDao gttpd = new GSTemporaryProductDao();
        try {
            if (GSBaseConstants.PLANPRICE.equals("true")) {//计划价的情况
                //planrice(aForm, processor, form, context, index, rid, array, flag, gttpd);
            } else {
                noPlanrice(aForm, processor, form, context, index, rid, array, flag, gttpd);

            }
        } catch (GSException e) {
            GSLogWriter.error(this, e.toString());
            aForm.getRequest().setAttribute("action", "A400335.do");
            aForm.getRequest().setAttribute("target", "_self");
            throw new GSException(e.getMessage());
        } finally {
            rst.setResult(array);
            aForm.getSession().setAttribute("manufactureExcel", rst);
        }
        return GSBaseConstants.FORWARD_SUCCESS;
    }

    /**
     * @param aForm
     * @param processor
     * @param form
     * @param context
     * @param index
     * @param rid
     * @param array
     * @param flag
     * @param gttpd
     * @throws Exception
     * @throws GSException
     */
    private void noPlanrice(GSBaseForm aForm, GSManufactureProcessor processor, GSManufactureAddForm4 form, LoginContext context, String[] index, String[] rid,
            ArrayList array, boolean flag, GSTemporaryProductDao gttpd) throws Exception, GSException {
    	DBConnection con = DBConnection.open();
        for (int a = 0; a < index.length; a++) {
            int i = 0;
            for (int tJ = 0; tJ < rid.length; tJ++) {
                if (index[a].equals(rid[tJ])) {
                    i = tJ;
                    break;
                }
            }
            boolean isAdd = false; //表示新增
            GSManufactureBean tbean = null;
            String temporaryConcentricityid = form.getGs_temporary_concentricity_id()[i];
            String manufactureCode = processor.getManufactureId(a);
            String category = form.getGs_manufacture_category_id()[i];
            String concentricityid = form.getGs_concentricity_id()[i];
            String manufactureName = form.getGs_manufacture_name()[i];
            String providerid = form.getGs_provider_id()[i];
            
            if(Integer.parseInt(GSSystemConfigurator.getParam("gs.is.concentricity"))==1){
                String name = GSBaseManager.getWareHoseNameByCode(temporaryConcentricityid);               
                if(name!=null&&!name.equals("")){
                    isAdd= true;
                }else
                    tbean = getTemporary(processor, form, a, i, temporaryConcentricityid);
            }else{
                if(temporaryConcentricityid.trim().length()<14){
                    isAdd= true;
                }else{
                    tbean = getTemporary(processor, form, a, i, temporaryConcentricityid);
                    getTemporary(processor, form, a, i, concentricityid);
                    if(gttpd.findByCode(tbean)){
                        throw new GSException("已成功写入: " + a + " 条产品信息;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;序号："
                                + form.getGs_manufacture_id()[i] + "的替换集中编码 " + temporaryConcentricityid + " 已经替换过一次，不能再次替换，请修改或移除！");   

                    }
                } 
            }
            
            if(!isAdd){
                if(!tbean.getGs_provider_id().equals(providerid)){
                    throw new GSException("已成功写入: " + a + " 条产品信息;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;序号："
                            + form.getGs_manufacture_id()[i] + "的替换集中编码 " + temporaryConcentricityid + "和集中编码"+concentricityid+" 的供应商编码不一致，不能再次替换，请修改或移除！");      
                }  
            }

            String unitprice = form.getGs_manufacture_unitprice()[i];
            String quantunit = form.getGs_quant_unit()[i];
            String manufacturetype = form.getGs_manufacture_type()[i];
            String manufacturespec = form.getGs_manufacture_spec()[i];
            String qualityassureperiod = form.getGs_quality_assure_period()[i];
            String manufacturername = form.getGs_manufacturer_name()[i];
            String makearea = form.getGs_make_area()[i];
            String manufacturebrand = form.getGs_manufacture_brand()[i];
            String drawingpiececode = form.getGs_drawing_piece_code()[i];
            String isbuy = form.getIs_buy()[i];
            if(isbuy.equals("0")){
                throw new GSException("已成功写入: " + a + " 条产品信息;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;序号："
                        + form.getGs_manufacture_id()[i] + "的集中编码 " + concentricityid + " 采购状态是不可采购，请修改或移除！");   
  
            }
            String machinetype = form.getGs_adapt_machine_type()[i];
            String property = form.getGs_appender_property()[i];
            String remark = form.getGs_remark()[i];
            String mode = form.getGs_balance_mode()[i];
            GSManufactureVO vo = new GSManufactureVO();
            vo.setGs_manufacture_id(manufactureCode);
            vo.setGs_concentricity_id(concentricityid);
            vo.setGs_manufacture_name(manufactureName);
            vo.setGs_manufacture_category_id(category);
            vo.setGs_manufacture_brand(manufacturebrand);
            vo.setGs_manufacture_type(manufacturetype);
            vo.setGs_manufacture_spec(manufacturespec);
            vo.setGs_manufacture_unitprice(unitprice);
            vo.setGs_quant_unit(quantunit);
            vo.setGs_quality_assure_period(qualityassureperiod);
            vo.setGs_manufacturer_name(manufacturername);
            vo.setGs_make_area(makearea);
            vo.setGs_provider_id(providerid);
            vo.setGs_adapt_machine_type(machinetype);
            vo.setGs_recorder_id(context.getUser().getCode());
            vo.setGs_manufacture_record_date(new DateUtil().getFullString());
            vo.setGs_is_tradeflat_manufacture("1");
            vo.setGs_appender_property(property);
            vo.setGs_remark(remark);
            vo.setGsValidity("1");
            vo.setGs_drawing_peice_code(drawingpiececode);
            vo.setIs_buy(isbuy);
            vo.setGs_balance_mode(mode);
            vo.setIsupdate(GSBaseConstants.IS_UPDATE);
            vo.setIs_normal(GSBaseConstants.NOT_NORMAL);
            vo.setCreate_user_id(context.getLoginUserId());
            vo.setCreate_user(context.getLoginUserName());
            vo.setCreate_time(new DateUtil().getFullString());
            vo.setLast_update_time(new DateUtil().getFullString());
            vo.setLast_update_user_id(context.getLoginUserId());
            vo.setLast_update_user(context.getLoginUserName());
            vo.setBalance_customer_code("0");
            vo.setPic(" ");
            vo.setRecent_adjustprice_date(new DateUtil().getFullString());
            vo.setRecent_adjusted_price(unitprice);
            vo.setGs_planprice(unitprice);
                vo.setWarehouse_code(tbean.getWarehouse_code());
                vo.setWarehouse_name(tbean.getWarehouse_name());  

            
            if(GSBaseConstants.PLANPRICE.equals("false")){
                vo.setGs_planprice(unitprice);
            }
            
            
            GSTemporaryProductBean svo = new GSTemporaryProductBean();
            if(!isAdd){
                svo.setConcentricity_code(vo.getGs_concentricity_id());
                svo.setTemporary_concentricity_code(temporaryConcentricityid);
                svo.setWarehouse_code(tbean.getWarehouse_code());
                svo.setWarehouse_name(tbean.getWarehouse_name());
                svo.setCreate_time(vo.create_time);
                svo.setCreate_user(vo.create_user);
                svo.setCreate_user_id(vo.create_user_id);
                svo.setLast_update_time(vo.getLast_update_time());
                svo.setLast_update_user(vo.getLast_update_user());
                svo.setLast_update_user_id(vo.getLast_update_user_id());                
            }
            
            

            
            
            // 判断是否存在相同集中编码的材料信息
            if (concentricityid.trim().length() != GSBaseConstants.PRODUCT_CONCENTRICITY&&Integer.parseInt(GSSystemConfigurator.getParam("gs.is.concentricity"))==0) {
                throw new GSException("已成功写入: " + a + " 条产品信息;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;序号："
                        + form.getGs_manufacture_id()[i] + "的集中编码 " + vo.gs_concentricity_id + " 已长度必须为"
                        + GSBaseConstants.TEMPORARY_PRODUCT_CONCENTRICITY + "位，<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;请修改或移除！");
            }
            GSManufactureBean mbean = processor.getManufInfoByConcentricityId(concentricityid);
            if (mbean == null) {
                 throw new GSException("已成功写入: " + a + " 条产品信息;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;序号："
                            + form.getGs_manufacture_id()[i] + "的集中编码 " + concentricityid
                            + " 不存在，<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;不能写入，请修改或移除！");
            }  
            GSManufactureBean mbeanTemp = processor.getManufInfoByConcentricityId(temporaryConcentricityid);
            if (mbeanTemp == null) {
                throw new GSException("已成功写入: " + a + " 条产品信息;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;序号："
                           + form.getGs_manufacture_id()[i] + "的集中编码 " +temporaryConcentricityid
                           + " 不存在，<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;不能写入，请修改或移除！");
           }  

            boolean bl = true;

//            if(flag){
//                bl = processor.modifyManufacture(vo); 
//            }else{
//                bl = processor.saveManufacture(vo);  
//            }
              
            
            if (bl) {                       
               try {
                 if(!isAdd){
                	String warehouseCode = svo.getWarehouse_code();
            	    ObjectList warehouseList = Warehouse.fetchAllOrgsByOwnWarehouseCode(con,warehouseCode );
                	if(warehouseList!=null&&warehouseList.size()>1){
                		for(int ii=0;ii<warehouseList.size();ii++){
                			Warehouse warehouse = (Warehouse)warehouseList.get(ii);
                			if(warehouse.getCode().equals(warehouseCode)){
                				continue;
                			}
                			svo.setWarehouse_code(warehouse.getCode());
                			svo.setWarehouse_name(warehouse.getName());
                			gttpd.saveByCon(svo,con);
                		} 
                	}else {
            	       gttpd.saveByCon(svo,con);  
                	}
                 }
               } catch (Exception e) {
                   processor.deleteManufacture(vo);
                   throw e;
               }
 
                // 移除
                int row = array.size();
                for (int j = 0; j < row; j++) {
                    GSTemporaryManufactureView mv = (GSTemporaryManufactureView) array.get(j);
                    if (index[a].equals(mv.getGs_recorder_id())) {
                        array.remove(mv);
                        break;
                    }
                }
            }
        }
        con.commit();
        if (array != null && array.size() == 0) {
            aForm.getSession().removeAttribute("manufactureExcel");
            aForm.getRequest().setAttribute("message", "产品确认写入成功，无可确认产品信息，返回继续添加。");
            if(flag){
                aForm.getRequest().setAttribute("action", "A400337.do"); 
            }else
               aForm.getRequest().setAttribute("action", "A400337.do");
        } else if (array != null && array.size() > 0) {
            aForm.getRequest().setAttribute("message", "产品确认写入成功");
            if (aForm.getRequest().getParameter("choice").equals("")) {
                  aForm.getRequest().setAttribute("action", "A400335.do");
            }
        }
    }

    /**
     * @param processor
     * @param form
     * @param a
     * @param i
     * @param vo
     * @param temporaryConcentricityid
     * @return
     * @throws GSException
     */
    private GSManufactureBean getTemporary(GSManufactureProcessor processor, GSManufactureAddForm4 form, int a, int i,
            String temporaryConcentricityid) throws GSException {
        GSManufactureBean tbean = processor.getManufInfoByConcentricityId(temporaryConcentricityid);
        if(tbean==null){
            throw new GSException("已成功写入: " + a + " 条产品信息;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;序号："
                    + form.getGs_manufacture_id()[i] + "的替换集中编码 " + temporaryConcentricityid + " 数据库中不存在请修改或移除！");   
        }else if(tbean.getAuditing_status().equals("3")){
            throw new GSException("已成功写入: " + a + " 条产品信息;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;序号："
                    + form.getGs_manufacture_id()[i] + "的替换集中编码 " + temporaryConcentricityid + " 已经注销，请修改或移除！");   
        }else if(tbean.getGs_validity().equals("0")){
            throw new GSException("已成功写入: " + a + " 条产品信息;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;序号："
                    + form.getGs_manufacture_id()[i] + "的替换集中编码 " + temporaryConcentricityid + " 状态是无效的，请修改或移除！");   
        }else if(tbean.getIs_buy().equals("0")){
            throw new GSException("已成功写入: " + a + " 条产品信息;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;序号："
                    + form.getGs_manufacture_id()[i] + "的替换集中编码 " + temporaryConcentricityid + " 是不可采购的，请修改或移除！");   
        }
        return tbean;
    }
}
